import { system, user } from "../api";

interface CacheData {
  data: any;
  timestamp: number;
}

// 默认系统配置，作为最后的降级方案
const DEFAULT_CONFIG = {
  data: {
    "ldap-enabled": "0",
    "system-api-url": "",
    "system-h5-url": "",
    "system-logo": "",
    "system-name": "PlayEdu",
    "system-pc-url": "",
    "system-pc-index-footer-msg": "",
    "player-poster": "",
    "player-is-enabled-bullet-secret": "0",
    "player-disabled-drag": "0",
    "player-bullet-secret-text": "",
    "player-bullet-secret-color": "",
    "player-bullet-secret-opacity": ""
  }
};

class ConfigCache {
  private readonly CACHE_DURATION = 30 * 60 * 1000; // 30分钟缓存（延长缓存时间）
  private readonly CONFIG_CACHE_KEY = 'system_config_cache';
  private readonly USER_CACHE_KEY = 'user_info_cache';
  
  // 请求队列，防止并发请求
  private configPromise: Promise<any> | null = null;
  private userPromise: Promise<any> | null = null;
  
  // 请求频率限制
  private lastConfigRequest = 0;
  private lastUserRequest = 0;
  private readonly MIN_REQUEST_INTERVAL = 3000; // 减少到3秒最小请求间隔

  private isValidCache(cache: CacheData | null): boolean {
    if (!cache) return false;
    const now = Date.now();
    return (now - cache.timestamp) < this.CACHE_DURATION;
  }

  private canMakeRequest(lastRequestTime: number): boolean {
    const now = Date.now();
    return (now - lastRequestTime) > this.MIN_REQUEST_INTERVAL;
  }

  private getFromStorage(key: string): CacheData | null {
    try {
      const cached = localStorage.getItem(key);
      return cached ? JSON.parse(cached) : null;
    } catch (error) {
      console.warn('缓存读取失败:', error);
      return null;
    }
  }

  private setToStorage(key: string, data: any): void {
    try {
      const cacheData: CacheData = {
        data,
        timestamp: Date.now()
      };
      localStorage.setItem(key, JSON.stringify(cacheData));
    } catch (error) {
      console.warn('缓存写入失败:', error);
    }
  }

  async getConfig(): Promise<any> {
    console.log('🔧 ConfigCache: 请求系统配置');
    
    const cached = this.getFromStorage(this.CONFIG_CACHE_KEY);
    if (this.isValidCache(cached)) {
      console.log('✅ ConfigCache: 使用缓存的系统配置');
      return cached!.data;
    }

    // 如果已有进行中的请求，直接返回
    if (this.configPromise) {
      console.log('⏰ ConfigCache: 等待进行中的配置请求');
      return this.configPromise;
    }

    // 频率限制检查
    if (!this.canMakeRequest(this.lastConfigRequest)) {
      console.log('⏰ ConfigCache: 请求过于频繁，使用缓存或默认配置');
      if (cached) {
        return cached.data;
      }
      // 如果没有缓存，返回默认配置
      console.log('🔄 ConfigCache: 没有缓存，使用默认配置');
      return DEFAULT_CONFIG;
    }

    // 创建新的请求
    this.configPromise = this.fetchConfig();
    
    try {
      const result = await this.configPromise;
      return result;
    } catch (error) {
      console.error('❌ ConfigCache: 配置请求失败，使用降级方案:', error);
      
      // 尝试返回缓存
      if (cached) {
        console.log('🔄 ConfigCache: 使用过期缓存');
        return cached.data;
      }
      
      // 最后的降级方案：返回默认配置
      console.log('🛡️ ConfigCache: 使用默认配置作为降级方案');
      return DEFAULT_CONFIG;
    } finally {
      // 请求完成后清除promise
      this.configPromise = null;
    }
  }

  private async fetchConfig(): Promise<any> {
    try {
      console.log('🚀 ConfigCache: 从服务器获取系统配置');
      this.lastConfigRequest = Date.now();
      
      const configRes = await system.config();
      this.setToStorage(this.CONFIG_CACHE_KEY, configRes);
      return configRes;
    } catch (error) {
      console.error('❌ ConfigCache: 获取系统配置失败:', error);
      // 如果有过期缓存，仍然使用
      const cached = this.getFromStorage(this.CONFIG_CACHE_KEY);
      if (cached) {
        console.log('🔄 ConfigCache: 使用过期缓存的系统配置');
        return cached.data;
      }
      throw error;
    }
  }

  async getUserInfo(): Promise<any> {
    console.log('👤 ConfigCache: 请求用户信息');
    
    const cached = this.getFromStorage(this.USER_CACHE_KEY);
    if (this.isValidCache(cached)) {
      console.log('✅ ConfigCache: 使用缓存的用户信息');
      return cached!.data;
    }

    // 如果已有进行中的请求，直接返回
    if (this.userPromise) {
      console.log('⏰ ConfigCache: 等待进行中的用户请求');
      return this.userPromise;
    }

    // 频率限制检查
    if (!this.canMakeRequest(this.lastUserRequest)) {
      console.log('⏰ ConfigCache: 用户请求过于频繁，使用缓存');
      if (cached) {
        return cached.data;
      }
      // 对于用户信息，如果没有缓存就等待
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    // 创建新的请求
    this.userPromise = this.fetchUserInfo();
    
    try {
      const result = await this.userPromise;
      return result;
    } finally {
      // 请求完成后清除promise
      this.userPromise = null;
    }
  }

  private async fetchUserInfo(): Promise<any> {
    try {
      console.log('🚀 ConfigCache: 从服务器获取用户信息');
      this.lastUserRequest = Date.now();
      
      const userRes = await user.detail();
      this.setToStorage(this.USER_CACHE_KEY, userRes);
      return userRes;
    } catch (error) {
      console.error('❌ ConfigCache: 获取用户信息失败:', error);
      // 如果有过期缓存，仍然使用
      const cached = this.getFromStorage(this.USER_CACHE_KEY);
      if (cached) {
        console.log('🔄 ConfigCache: 使用过期缓存的用户信息');
        return cached.data;
      }
      throw error;
    }
  }

  // 清除缓存
  clearCache(): void {
    console.log('🧹 ConfigCache: 清除所有缓存');
    localStorage.removeItem(this.CONFIG_CACHE_KEY);
    localStorage.removeItem(this.USER_CACHE_KEY);
    // 重置请求时间
    this.lastConfigRequest = 0;
    this.lastUserRequest = 0;
    // 清除进行中的请求
    this.configPromise = null;
    this.userPromise = null;
  }

  // 清除过期缓存
  clearExpiredCache(): void {
    const configCache = this.getFromStorage(this.CONFIG_CACHE_KEY);
    const userCache = this.getFromStorage(this.USER_CACHE_KEY);
    
    if (configCache && !this.isValidCache(configCache)) {
      localStorage.removeItem(this.CONFIG_CACHE_KEY);
    }
    
    if (userCache && !this.isValidCache(userCache)) {
      localStorage.removeItem(this.USER_CACHE_KEY);
    }
  }

  // 强制刷新缓存
  forceRefresh(): void {
    console.log('🔄 ConfigCache: 强制刷新缓存');
    this.clearCache();
  }
}

export const configCache = new ConfigCache(); 